package com.gw2.gw2world.controller;

import java.io.Serializable;

import com.gw2.gw2world.R;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ServerManager implements OnClickListener, Serializable {
	private static final long serialVersionUID = 1L;
	private static final int HOME=0x1000, GUEST1=0x2000, GUEST2=0x4000, CHECKED=0x8000;
	public static final boolean MODE_AUTOCOMMIT=true, MODE_USERCOMMIT=false;
	DatabaseOpenHelper dbHelper;
	private Context mContext;
	private SharedPreferences prefs;
	private SharedPreferences.Editor editor;
	private Button b_region, b_ok_server;
	private RelativeLayout rl_server;
	private GridLayout gl_servers;
	private boolean autocommit=MODE_AUTOCOMMIT;
	
	/** Initialize server manager
	 * @param c Activity context
	 */
	public ServerManager(Context c) {
		mContext=c;
		prefs=PreferenceManager.getDefaultSharedPreferences(mContext);
		dbHelper = new DatabaseOpenHelper(mContext, "database", null, 1);
	}
	/** UI mode
	 * @param m Use constants MODE_AUTOCOMMIT to save in shared preferences on changes or MODE_USERCOMMIT if user should validate with OK button
	 */
	public void setMode(boolean m) { autocommit=m; }
	public void setOnOkClickListener(View.OnClickListener l) {
		b_ok_server.setOnClickListener(l);
	}
	public boolean isHomeSelected() {
		for(int i=0;i<gl_servers.getChildCount(); i++)
			if(gl_servers.getChildAt(i).getClass()==ImageView.class) {
				int tmp=(Integer)gl_servers.getChildAt(i).getTag();
				if((tmp&(HOME|CHECKED))==(HOME|CHECKED)) {
					return true;
				}
			}
		return false;
	}
	/** Writes servers ID to shared preferences.
	 * @return false if the home server is not selected
	 */
	public boolean writePreferences() {
		editor=prefs.edit();
		for(int i=0;i<gl_servers.getChildCount(); i++)
			if(gl_servers.getChildAt(i).getClass()==ImageView.class) {
				int tmp=(Integer)gl_servers.getChildAt(i).getTag();
				if((tmp&(HOME|CHECKED))==(HOME|CHECKED)) editor.putInt("home_server", tmp&0x0fff);
				else if((tmp&(GUEST1|CHECKED))==(GUEST1|CHECKED)) editor.putInt("guest1_server", tmp&0x0fff);
				else if((tmp&(GUEST2|CHECKED))==(GUEST2|CHECKED)) editor.putInt("guest2_server", tmp&0x0fff);
			}
		editor.commit();
		if(prefs.getInt("home_server", 0)==0) {
			Toast.makeText(mContext, R.string.msg_select_server, Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
	public int getOkButtonId() {return R.id.b_ok_server; }
	/** Get the server list and generate UI  */
	private void getServerList() {
		String sel=prefs.getString("region", "na").equals("na")?"<2000":">1999";
		Cursor c=dbHelper.getReadableDatabase().query("server", null, "lang=? AND id"+sel, new String[]{prefs.getString("language", "en")}, null, null, "id");
		gl_servers.removeAllViews();
		gl_servers.setRowCount(c.getCount());
		/* ID encoding
		 * Server ID are from 10## to 23# => Hex values are 0x0####
		 * home/guest1/guest2/checked will be encoded in 0x#000
		 * 0x1000: home
		 * 0x2000: guest1
		 * 0x4000: guest2
		 * 0x8000: checked
		 */
		while(c.moveToNext()) {
			int id=c.getInt(0);
			ImageView iv=new ImageView(mContext);
			iv.setImageResource(R.drawable.home);
			iv.setClickable(true);
			iv.setTag(Integer.valueOf(id|HOME));
			if(prefs.getInt("home_server", 0)!=id) iv.setAlpha(0.25f);
			else iv.setTag(Integer.valueOf(id|HOME|CHECKED));
			iv.setOnClickListener(this);
			gl_servers.addView(iv);
			iv=new ImageView(mContext);
			iv.setImageResource(R.drawable.guest);
			iv.setClickable(true);
			iv.setTag(Integer.valueOf(id|GUEST1));
			if(prefs.getInt("guest1_server", 0)!=id) iv.setAlpha(0.25f);
			else iv.setTag(Integer.valueOf(id|GUEST1|CHECKED));
			iv.setOnClickListener(this);
			gl_servers.addView(iv);
			iv=new ImageView(mContext);
			iv.setImageResource(R.drawable.guest);
			iv.setClickable(true);
			iv.setTag(Integer.valueOf(id|GUEST2));
			if(prefs.getInt("guest2_server", 0)!=id) iv.setAlpha(0.25f);
			else iv.setTag(Integer.valueOf(id|GUEST2|CHECKED));
			iv.setOnClickListener(this);
			gl_servers.addView(iv);
			TextView tv=new TextView(mContext);
			tv.setText(c.getString(2));
			GridLayout.LayoutParams params =new GridLayout.LayoutParams();
			params.setGravity(Gravity.CENTER_VERTICAL);
			gl_servers.addView(tv,params);
		}
	}
	/** Uncheck column and line from the given ID
	 * @param id Encoded ID
	 */
	private void uncheck(int id) {
		int type=id&(HOME|GUEST1|GUEST2);
		id=id&0x0fff;
		for(int i=0;i<gl_servers.getChildCount(); i++)
			if(gl_servers.getChildAt(i).getClass()==ImageView.class) {
				int tmp=(Integer)gl_servers.getChildAt(i).getTag();
				if((tmp&type)==type) { //uncheck by column
					gl_servers.getChildAt(i).setAlpha(0.25f);
					gl_servers.getChildAt(i).setTag(Integer.valueOf(tmp&(0xffff-CHECKED)));
				}
				if((tmp&0x0fff)==id) { //uncheck by line
					gl_servers.getChildAt(i).setAlpha(0.25f);
					gl_servers.getChildAt(i).setTag(Integer.valueOf(tmp&(0xffff-CHECKED)));
				}
			}
	}
	public View getView() {
		LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v=inflater.inflate(R.layout.server_selector, null/*parent*/, false);
		b_region=(Button)v.findViewById(R.id.b_region);
		if(prefs.getString("region", "na").equals("eu")) b_region.setText(R.string.eu);
		b_region.setOnClickListener(this);
		b_ok_server=(Button)v.findViewById(R.id.b_ok_server);
		if(autocommit==MODE_USERCOMMIT) b_ok_server.setVisibility(View.VISIBLE);
		else  b_ok_server.setVisibility(View.GONE);
		rl_server=(RelativeLayout)v.findViewById(R.id.rl_servers);
		rl_server.setVisibility(View.VISIBLE);
		gl_servers=(GridLayout)v.findViewById(R.id.gl_servers);
		getServerList();
		if(isHomeSelected()) b_ok_server.setEnabled(true);
		return v;
	}
	@Override
	public void onClick(View v) {
		if(v.getId()==R.id.b_region) {
			editor=prefs.edit();
			if(prefs.getString("region", "na").equals("na")) {
				editor.putString("region", "eu");
				b_region.setText(R.string.eu);
			} else {
				editor.putString("region", "na");
				b_region.setText(R.string.na);
			}
			editor.commit();
			getServerList();
		} else if(v.getClass()==ImageView.class) { //Clicked ImageView
			int id=(Integer)v.getTag();
			uncheck(id);
			v.setAlpha(1f);
			v.setTag(Integer.valueOf(id|CHECKED));
			b_ok_server.setEnabled(false);
			if(isHomeSelected()) b_ok_server.setEnabled(true);
		}
	}
}
